<template>
  <div class="personalSettingLevel_container pl-1 pr-1 ">
		<div class="personalSettingLevel_container_level padding-1 mb-1 br-16">
			<div class="container_level_title">
				<img :src="userLevelIcon" class="mr-0" alt="">
				<span>{{ userLevelName }}</span>
			</div>
			<button @click="clickInvite">{{ $t("立即邀请") }}</button>
			<div class="container_level_progress pl-1 pr-1">
				<div class="container_level_progress_left" @click="clickCopyInviteLink()">
					<span class="mr-0">{{ $t("邀请链接") }}</span>
					<img src="@/image/homePage/aiImageDetail/cope.png"  alt="">
				</div>
				<div class="container_level_progress_left" @click="clickCopyInviteCode()">
					<span class="mr-0">{{ this.userInfo.UID }}</span>
					<img src="@/image/homePage/aiImageDetail/cope.png"  alt="">
				</div>
			</div>
		</div>
		<div class="personalSettingLevel_container_nums br-16 padding-1 mb-0">
			<div class="personalSettingLevel_container_nums_top mb-2">
				<div class="nums_top_left">
					<img src="@/image/personalCenter/setting/level/icon2.png" alt="">
					<div class="nums_top_left_content">
						<div class="nums_top_left_content_title">
							<span>{{ userInfo.inviteNums.firend }}</span>&nbsp;
							<span>{{ $t("人") }}</span>
						</div>
						<div class="nums_top_left_content_label">{{ $t("我的好友") }}</div>
					</div>
				</div>
				<div class="nums_top_border"></div>
				<div class="nums_top_left">
					<img src="@/image/personalCenter/setting/level/icon2.png" alt="">
					<div class="nums_top_left_content">
						<div class="nums_top_left_content_title">
							<span>{{ userInfo.inviteNums.team }}</span>&nbsp;
							<span>{{ $t("人") }}</span>
						</div>
						<div class="nums_top_left_content_label">{{ $t("我的团队") }}</div>
					</div>
				</div>
			</div>
			<div class="personalSettingLevel_container_nums_bottom">
				<div class="nums_bottom_item">
					<span>{{ $t("普通会员") }}</span>
					<span class="nums_bottom_item_sps">{{ userInfo.inviteNums.common + " " + $t("人") }}</span>
				</div>
				<div class="nums_bottom_item">
					<span>{{ $t("T1") }}</span>
					<span class="nums_bottom_item_sps">{{ userInfo.inviteNums.t1 + " " + $t("人") }}</span>
				</div>
				<div class="nums_bottom_item">
					<span>{{ $t("T2") }}</span>
					<span class="nums_bottom_item_sps">{{ userInfo.inviteNums.t2 + " " + $t("人") }}</span>
				</div>
				<div class="nums_bottom_item">
					<span>{{ $t("T3") }}</span>
					<span class="nums_bottom_item_sps">{{ userInfo.inviteNums.t3 + " " + $t("人") }}</span>
				</div>
				<div class="nums_bottom_item">
					<span>{{ $t("T4") }}</span>
					<span class="nums_bottom_item_sps">{{ userInfo.inviteNums.t4 + " " + $t("人") }}</span>
				</div>
			</div>
		</div>
		<div class="personalSettingLevel_container_grid mb-0">
			<div class="personalSettingLevel_container_grid_item padding-1 br-16">
				<div class="grid_item_icon mb-0">
					<img src="@/image/personalCenter/setting/level/icon6.png" alt="">
				</div>
				<div class="grid_item_title mb-1">{{ $t("直属有效人数") }}</div>
				<div class="grid_item_content">{{ userInfo.inviteNums.directlyNums }}</div>
			</div>
			<div class="personalSettingLevel_container_grid_item padding-1 br-16">
				<div class="grid_item_icon mb-0">
					<img src="@/image/personalCenter/setting/level/icon7.png" alt="">
				</div>
				<div class="grid_item_title mb-1">{{ $t("直属质押金额") }}</div>
				<div class="grid_item_content">
					<span class="mr-0">{{ userInfo.inviteNums.directlyMoney }}</span>
					<span class="grid_item_content_sps">{{ $t("SUSD") }}</span>
				</div>
			</div>
			<div class="personalSettingLevel_container_grid_item padding-1 br-16">
				<div class="grid_item_icon mb-0">
					<img src="@/image/personalCenter/setting/level/icon8.png" alt="">
				</div>
				<div class="grid_item_title mb-1">{{ $t("团队有效人数") }}</div>
				<div class="grid_item_content">{{ userInfo.inviteNums.teamNums }}</div>
			</div>
		</div>
		<div class="personalSettingLevel_container_grids mb-1">
			<div class="personalSettingLevel_container_grid_item padding-1 br-16">
				<div class="grid_item_icon mb-0">
					<img src="@/image/personalCenter/setting/level/icon4.png" alt="">
				</div>
				<div class="grid_item_title mb-1">{{ $t("您的奖励") }}</div>
				<div class="grid_item_content">
					<span class="mr-0">{{ userInfo.inviteNums.award }}</span>
					<span class="grid_item_content_sps">{{ $t("SAT") }}</span>
				</div>
			</div>
			<div class="personalSettingLevel_container_grid_item padding-1 br-16">
				<div class="grid_item_icon mb-0">
					<img src="@/image/personalCenter/setting/level/icon7.png" alt="">
				</div>
				<div class="grid_item_title mb-1">{{ $t("您的业绩") }}</div>
				<div class="grid_item_content">
					<span class="mr-0">{{ userInfo.inviteNums.performance }}</span>
					<span class="grid_item_content_sps">{{ $t("SUSD") }}</span>
				</div>
			</div>
		</div>
		<div class="personalSettingLevel_container_tabs mb-1">
			<van-tabs v-model="tabsActive" animated color="#FFFFFF" background="#0C1527" title-active-color="#0086FF" line-height="0" @change="tabsChange">
				<van-tab v-for="(item , index) in tasList" :key="index" :title="item.name" :name="index+1">
					<!-- 邀请记录 -->
					<div class="invite_record_page" v-if="tabsActive == 1" >
						<van-tabs v-model="inviteRecordActive" animated color="#FFFFFF" background="#101D34" title-active-color="#FFFFFF" line-height="0" @change="inviteRecordTabsChange" @touchmove.native.stop>
							<van-tab v-for="(invitedRecordTabItem , invitedRecordTabIndex) in showingInviteRecordTabs" :key="invitedRecordTabIndex" :title="invitedRecordTabItem.name" :name="invitedRecordTabIndex">
								<div v-if="inviteRecordList.length">
									<van-list
										v-model="loading"
										:finished="finished"
										:finished-text="$t('没有更多了')"
										@load="onInviteRecordLoad"
										>
										<div class="history_list br-16 pr-1 pl-1 ">
											<div class="history_list_item pb-1 pt-1" v-for="(inviteRecordItem,inviteRecordItemIndex) in inviteRecordList" :key="inviteRecordItemIndex">
												<div class="history_list_invite_record_item_left">
													<div class="history_list_item_left_big mb-0">{{ inviteRecordItem.nickname }}</div>
													<div>{{ inviteRecordItem.createtime }}</div>
												</div>
												<div class="history_list_invite_record_item_right">
													<div class="history_list_itme_right_big">{{ Number(inviteRecordItem.money).toFixed(0) + ' ' + inviteRecordItem.currency }}</div>
													<img class="history_list_item_right_level" v-if="inviteRecordItem.is_effective" :src="levelIcon(inviteRecordItem.level)" alt="">
													<div class="history_list_itme_right_small" v-else>{{ "valid" }}</div>
												</div>
											</div>
										</div>
									</van-list>
								</div>
							</van-tab>
						</van-tabs>
						<img v-if="inviteRecordList.length <= 0" class="emptyImg" src="@/image/personalCenter/setting/level/data.png" alt="">
					</div>

					<!-- 投资记录 -->
					<div v-if="tabsActive == 2">
						<div v-if="recordList.length">
							<van-list
								v-model="loading"
								:finished="finished"
								:finished-text="$t('没有更多了')"
								@load="onLoad"
								>
								
								<div class="history_list br-16 pr-1 pl-1 ">
									<div class="history_list_item pb-1 pt-1" v-for="(val,index) in recordList" :key="index">
										<div class="history_list_invite_record_item_left">
											<div class="history_list_item_left_big mb-0">{{ val.nickname }}</div>
											<div>{{ val.createtime }}</div>
										</div>
										<div class="history_list_invite_record_item_right">
											<div class="history_list_itme_right_small">{{ $t('量化投资') }}</div>
											<div class="history_list_itme_right_big">{{ Number(val.money).toFixed(0) + ' ' + val.currency }}</div>
										</div>
									</div>
								</div>
							</van-list>
						</div>
						<img v-if="recordList.length <= 0" class="emptyImg" src="@/image/personalCenter/setting/level/data.png" alt="">
					</div>

					<!-- 返佣记录 -->
					<div v-if="tabsActive == 3">
						<div v-if="recordList.length">
							<van-list
								v-model="loading"
								:finished="finished"
								:finished-text="$t('没有更多了')"
								@load="onLoad"
								>
								
								<div class="history_list br-16 pr-1 pl-1 ">
									<div class="history_list_item pb-1 pt-1" v-for="(val,index) in recordList" :key="index">
										<div class="history_list_invite_record_item_left">
											<div class="history_list_item_left_big mb-0">{{ val.type }}</div>
											<div>{{ val.created }}</div>
										</div>
										<div class="history_list_invite_record_item_right">
											<div class="history_list_itme_right_big">{{ Number(val.money).toFixed(4) + ' ' + val.currency }}</div>
											<div class="history_list_itme_right_small">{{ $t('返佣统计') }}</div>
										</div>
									</div>
								</div>
							</van-list>
						</div>
						<img v-if="recordList.length <= 0" class="emptyImg" src="@/image/personalCenter/setting/level/data.png" alt="">
					</div>

					<!-- 团队记录 -->
					<div class="team_record_page" v-if="tabsActive == 4">
						<van-tabs v-model="teamRecordActive" animated color="#FFFFFF" background="#101D34" title-active-color="#FFFFFF" line-height="0" @change="teamRecordTabsChange" @touchmove.native.stop>
							<van-tab v-for="(teamRecordTabItem , teamRecordTabIndex) in teamRecordTabs" :key="teamRecordTabIndex" :title="teamRecordTabItem.name" :name="teamRecordTabIndex">
								<van-list class="team_record_list mt-1" v-model="loading" @load="onTeamRecordLoad" :finished="finished">
										<div class="team_record_item" v-for="(teamRecordItem,teamRecordIndex) in teamRecordList" :key="teamRecordIndex">
											<div :class="'team_record_item_data pt-1 pb-1 pr-1 pl-1 br-8' + (teamRecordIndex == 0 ? '' : ' mt-1')">
												<div class="team_record_item_title">
													{{ teamRecordIndex == 0 ? $t('所有数据') : $t('等级')+' '+teamRecordIndex }}
												</div>
												<div class="team_record_item_content br-16">
													<div class="team_record_item_content_left">
														<div class="team_record_item_content_up_num">{{ teamRecordItem.count }}</div>
														<div class="team_record_item_content_down_text">{{ $t('团队规模') }}</div>
													</div>
													<div class="team_record_item_content_right">
														<div class="team_record_item_content_up_num">{{ teamRecordItem.money }}</div>
														<div class="team_record_item_content_down_text">{{ $t('订单收益') }}</div>
													</div>
												</div>
											</div>
											<img v-if="teamRecordIndex == 0" class="team_record_item_line mt-1" src="@/image/personalCenter/setting/level/line.png" alt="">
										</div>

										
									</van-list>
							</van-tab>
						</van-tabs>
					</div>
				</van-tab>
			</van-tabs>
		</div>

		<!-- 立即邀请海报 -->
		<van-popup v-model="popupShow">
			<img class="personalSettingLevel_van_popup_img mb-0" :src="combinedImageUrl || posterUrl" alt="">
			<div class="personalSettingLevel_van_popup_btns">
				<button class="copyBtn" @click="()=>clickCopyInviteLink()">{{ $t("复制链接") }}</button>
				<button class="saveBtn" @click="()=>downloadImage('poster.png')">{{ $t("保存海报") }}</button>
			</div>
		</van-popup>
	</div>
</template>

<script>
import { clipboard } from '@/utils';
import { inviteFriends , inviteFriendsList } from '@/request/personalCenter'
import QRCode from 'qrcode'
import BusinessUtils from '@/utils/business';
import tr from '@/lang/MUI/tr';
export default {
	name: 'PersonalSettingLevel',
	data(){
		return{
			userInfo:{
				level: 0,
				UID: '6680242119',
				invtiveLink: "https://www.baidu.com/index.htm",
				inviteNums:{
					firend: 1,
					team: 2,
					common: 3,
					t1: 4,
					t2: 5,
					t3: 6,
					t4: 7,
					directlyNums:0,
					directlyMoney:0,
					teamNums:0,
					award: 0,
					performance: 0,
				}
			},
			tabsActive: this.$t('邀请记录'),
			tasList:[
				{
					name: this.$t('邀请记录'),
					value: []
				},
				{
					name: this.$t('投资记录'),
					value:[],
				},
				{
					name: this.$t('返佣记录'),
					value:[],
				},
				{
					name: this.$t('团队记录'),
					value:[],
				}
			],
			recordList:[],

			isLevelOn: false, // 等级功能是否开启
			inviteRecordActive: 0,
			inviteRecordTabs: [
				{ name: this.$t('全部') },
				{ name: this.$t('有效') },
				{ name: this.$t('无效') },
				{ name: 'S1' },
				{ name: 'S2' },
				{ name: 'S3' },
				{ name: 'S4' },
				{ name: 'T1' },
				{ name: 'T2' },
				{ name: 'T3' },
			],
			inviteRecordList: [],

			teamRecordActive: 0,
			teamRecordTabs: [
				{ name: this.$t('全部') },
				{ name: this.$t('日') },
				{ name: this.$t('周') },
				{ name: this.$t('年') },
			],
			teamRecordList: [],

			popupShow: false,
			posterUrl: require('@/image/personalCenter/setting/level/banner.jpg'),
			total: 0,
			limit: 20,
			loading: false,
			finished: false,
			combinedImageUrl: null,
			canvasWidth: 375, 
			canvasHeight: 667  
		}
	},
	mounted(){
		this.resetLimit()
		this.inviteFriends()
	},
	computed:{
		userLevelName(){
			return this.$t("{level} 会员",{level:BusinessUtils.getLevelName(this.userInfo.level)}) 
		},

		userLevelIcon(){
			if(this.userInfo.level <= 4) {
				return require('@/image/personalCenter/setting/level/level_icon1.png');
			}else {
				return require('@/image/personalCenter/setting/level/level_icon2.png');
			}
		},

		showingInviteRecordTabs() {
			if(!this.isLevelOn) {
				return this.inviteRecordTabs.slice(0, 3);
			}else {
				return this.inviteRecordTabs;
			}
		}
	},
	methods: {
		// ---------------通用功能----------------
		levelIcon(levelId){
			return BusinessUtils.getLevelIcon(levelId)
		},

		// ---------------上部内容----------------
		// 邀请好友
		inviteFriends(){
			inviteFriends().then(res=>{
				console.log(res , 1)
				if(res.code == 1){
					let data = res.data

					this.isLevelOn = data.user_level_switch == 1; // 等级功能是否开启

					// 邀请链接
					this.userInfo.UID = data.code
					this.userInfo.id = data.user_id
					this.userInfo.invtiveLink = data.url
					this.userInfo.level = data.user_level
					this.userInfo.inviteNums = {
						// 邀请人数数据
						firend: data.push_num,
						team: data.my_team_num,
						common: data.level_list.S0,
						t1: data.level_list.T1,
						t2: data.level_list.T2,
						t3: data.level_list.T3,
						t4: data.level_list.T4,
						// 有效
						directlyNums: data.zhi_youxiao || 0,
						directlyMoney: data.zhi_money || 0,
						teamNums: data.team_youxiao || 0,
						award: data.jiangli || 0,
						performance: data.yeji || 0,
					}

					this.generateCombinedImage()
				}
			})
			this.tabsChange(1)
		},

		// ----------------邀请相关----------------

		async generateCombinedImage() {
			// 创建canvas元素
			const canvas = document.createElement('canvas')
			canvas.width = this.canvasWidth
			canvas.height = this.canvasHeight
			const ctx = canvas.getContext('2d')
			
			// 1. 加载海报图片
			const posterImg = new Image()
			posterImg.crossOrigin = 'Anonymous'
			posterImg.src = this.posterUrl
			
			await new Promise((resolve) => {
				posterImg.onload = resolve
			})
			
			// 2. 绘制海报
			ctx.drawImage(posterImg, 0, 0, this.canvasWidth, this.canvasHeight)
			
			// 3. 生成二维码
			const qrCanvas = document.createElement('canvas')
			console.log(this.userInfo.invtiveLink  ,1111)
			await QRCode.toCanvas(qrCanvas, this.getInviteLink(), {
				width: 60, // 二维码大小
				margin: 0
			})
			
			// 4. 将二维码绘制到海报右下角
			const qrSize = 60
			const qrX = this.canvasWidth - qrSize - 14 // 右边距17px
			const qrY = this.canvasHeight - qrSize - 15 // 底边距17px
			ctx.drawImage(qrCanvas, qrX, qrY, qrSize, qrSize)
			
			// 5. 将合并后的图片保存为DataURL
			this.combinedImageUrl = canvas.toDataURL('image/png')
			return this.combinedImageUrl
		},
		
		
		getInviteLink(){
			return BusinessUtils.getInvitePath(this.userInfo.invtiveLink, this.userInfo.UID)
		},
		clickCopyInviteLink(){
			// 复制邀请链接
			this.copyText(this.getInviteLink());
		},
		// 复制分发
		clickCopyInviteCode(){
			this.copyText(this.userInfo.UID);
		},
		// 复制
		async copyText(value) {
			try {
				await clipboard.copy(value);
				this.$toast.success(this.$t('复制成功'));
			} catch {
				this.$toast.fail(this.$t('复制失败'));
			}
		},
		async clickInvite(){
			try {
				// 生成带二维码的海报
				await this.generateCombinedImage()
				this.popupShow = true
			} catch (error) {
				console.error('生成海报失败:', error)
				this.$toast.fail('生成海报失败')
			}
		},
		// 本地图片，仅演示
		async downloadImage(filename) {
			if (!this.combinedImageUrl) {
				await this.generateCombinedImage()
			}

			try {
				const link = document.createElement('a')
				link.href = this.combinedImageUrl
				link.download = 'poster_with_qrcode.png'
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				this.$toast.success(this.$t('下载成功'))
			} catch (error) {
				console.error(this.$t('下载失败') + ':', error)
				this.$toast.fail(this.$t('下载失败'))
			}
		},

		//-----------底部记录---------------

		tabsChange(name , title){
			this.resetLimit()
			if(name == 1){
				this.inviteRecordTabsChange(0)
			}else if(name == 2){
				this.inviteFriendsList(name)
			}else if(name == 3){
				this.inviteFriendsList(name)
			}else if(name == 4){
				this.teamRecordTabsChange(0)
			}
		},

		resetLimit() {
			this.limit = 20
			this.total = 0
			this.loading = false
			this.finished = false
		},

		//-----------邀请记录---------------

		inviteRecordTabsChange(name , title){
			this.inviteRecordActive = name

			this.resetLimit()
			this.reqInviteRecord(name)
		},

		reqInviteRecord(inviteRecordType){
			// 请求邀请记录
			this.loading = true
			try {
				inviteFriendsList({type: 1,type_class:inviteRecordType, limit: this.limit}).then(res => {
					this.loading = false
					
					if(res.code == 1){
						this.total = res.data.data.total
						this.inviteRecordList = res.data.data.data.map(item=>{
							return {
								...item,
								currency: item.currency.toUpperCase(),
							}
						})
						
						if(this.inviteRecordList.length >= this.total){
							this.finished = true
						}else{
							this.finished = false
						}
					}
				})
			} catch (error) {
				this.loading = false
			}
			
		},

		onInviteRecordLoad(){
			if(this.limit <= this.total){
				this.limit += 15
				this.reqInviteRecord(this.inviteRecordActive)
			}else{
				this.finished = true
			}
		},

		//-----------投资记录、返佣记录-----------------
		inviteFriendsList(active){
			this.loading = true

			try{
				// 邀请好友列表
				inviteFriendsList({type: active,limit:this.limit}).then(res => {
					this.loading = false
					
					if(res.code == 1){
						// console.log(res.data , active , this.limit , '***********')
						this.total = res.data.data.total
						this.recordList = res.data.data.data.map(item=>{
							return {
								...item,
								currency: item.currency.toUpperCase(),
							}
						})
						
						if(this.recordList.length >= this.total){
							this.finished = true
						}else{
							this.finished = false
						}
					}
				})
			}catch(error){
				this.loading = false
			}
		},

		onLoad(){
			if(this.limit <= this.total){
				this.limit += 15
				this.inviteFriendsList(this.tabsActive)
			}else{
				this.finished = true
			}
		},

		// ---------------团队记录----------------
		teamRecordTabsChange(name , title){
			this.teamRecordActive = name

			this.resetLimit()
			this.reqTeamRecord(name)
		},

		reqTeamRecord(teamRecordType){
			// 请求团队记录
			this.loading = true
			try {
				inviteFriendsList({type: 4,type_class:teamRecordType}).then(res => {
					this.loading = false
					
					if(res.code == 1){
						this.teamRecordList = res.data.data.map(item=>{
							return {
								...item,
							}
						})
					}
				})
			} catch (error) {
				this.loading = false
			}
			
		},

		onTeamRecordLoad(){
			this.loading = false
		},


		//保存线上海报
		// async downloadImage(url) {
		// 	try {
		// 			const response = await fetch(url);
		// 			if (!response.ok) throw new Error('网络响应异常');
					
		// 			const blob = await response.blob();
		// 			const objectURL = URL.createObjectURL(blob);
					
		// 			const link = document.createElement('a');
		// 			link.href = objectURL;
		// 			link.download = url.substring(url.lastIndexOf('/') + 1);
		// 			document.body.appendChild(link);
		// 			link.click();
					
		// 			// 释放对象URL
		// 			setTimeout(() => {
		// 					URL.revokeObjectURL(objectURL);
		// 					document.body.removeChild(link);
		// 			}, 100);
					
		// 			this.$toast.success('开始下载');
		// 	} catch (error) {
		// 			console.error('下载失败:', error);
		// 			this.$toast.fail('下载失败，请重试');
		// 	}
    // },
	}
}
</script>

<style>

</style>